<template>
  <div class="cjy-classify-list">
    <div style="width: 100%;height: 100%" ref="outer">
      <translate-group :lengths="secList.length"
                       ref="translateGroup"

                       @changeIsReutrnPosition="changeIsReutrnPosition"
                       @pullDown="pullDown"
                       @getWrpperSize="getWrpperSize"
                       @scrollBottom="loadMores">
        <div style="width: 100%" :style="{paddingTop: paddingTop}">

          <div ref="tepSelectBox">
            <div v-if="!(isTepSelectBox && secList.length > 4)" style="width: 100%;height:2.2rem"></div>
            <tap-select-box
              v-if="isTepSelectBox && secList.length > 4 "
              :titleInfor="secList"
              @closeList="changesTepSelectBox(false)"
              style="width: 100%">
            </tap-select-box>
          </div>
          <item-list ref="itemList"
                     :topHeight="topHeight"
                     :wrpperHeight="wrpperHeight"
                     :wrpperTop="wrpperTop"
                     v-if="comDetailDataList  "
                     :comDetailDataList="comDetailDataList">
          </item-list>
          <div v-if="isOnLoad && comDetailDataList.length < goodsClassifyInfor[activeIndex].totalCount "
               style="color:#9a9a9a ;height:2rem!important;  width: 100%;text-align: center;  line-height: 2rem;vertical-align: middle ; background:white;font-weight: 600"
               @click.self="changeFloat">
            <LoadMoreAnimate></LoadMoreAnimate>
            加载更多
          </div>


          <div v-if="comDetailDataList.length <= 0 " class="centent" style="">
            <div class="no_data" style="min-height: 12.5rem">
              <img v-if="!isOnLoad" src="static/image/no_order.png" style="width:70%;">
              <p v-if="!isOnLoad">暂无相关数据</p>
            </div>
          </div>
          <div
            v-if=" comDetailDataList.length != 0 &&comDetailDataList.length == goodsClassifyInfor[activeIndex].totalCount "
            style="background:rgb(245,245,245);color: rgb(154,154,154);height:2rem ;line-height:2rem">
            —— 好东西都看完了——
          </div>
          <!--版权信息-->
          <div class="copyright"
               v-if=" comDetailDataList.length == 0 ||comDetailDataList.length == goodsClassifyInfor[activeIndex].totalCount ">
            <PageFoot></PageFoot>
          </div>
          <!--版权信息 end-->
        </div>
      </translate-group>
    </div>
  </div>
</template>

<script>
  import {mapActions, mapGetters, mapState} from 'vuex';
  import TapSelectBox from '@/real-components/TapSelectBox';
  import PageFoot from '@/real-components/PageFoot';
  import LoadMoreAnimate from '@/real-components/LoadMoreAnimate';
  import ItemList from './ItemList';
  import {queryGoodsList} from '../../../utils/ReturnAxios';
  import translateGroup from '../../../real-components/TranslateTest';
  import BannerGroup from '@/real-components/ClassifyBanner';
  import {showLoading, hideLoading} from '@/utils/loading';

  export default {
    data() {
      return {
        goodsClassifyInfor: [],
        comDetailDataList: [],
        pageSize: 5,
        currentPage: 1,
        orderType: '',
        orderDre: 1,
        isShowLoadMore: false,
        topHeight: 0,
        isTepSelectBox: true,
        tepSelectBoxHeight: 0,
        wrpperHeight: 0,
        wrpperTop: 0,
        isOnLoad: true,
        isReutrnPosition: false,
        isinitOver: false
      };
    },
    props: {
      secList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      goodsCode: {
        type: String,
        default: '',
      },
      paddingTop: {
        type: String,
        default: '2.2rem',
      },
    },
    components: {
      translateGroup,
      ItemList,
      BannerGroup,
      PageFoot,
      LoadMoreAnimate,
      TapSelectBox,
    },
    methods: {
      animateLodding() {
        showLoading();
        setTimeout(() => {
          hideLoading();
        }, 3000)
      },

      loadMores() {
        this.queryClassifyInfor(this.activeIndex, 'loadingMore');
      },
      //申请数据所用的 数据
      getConfig(goodsClassId, pageNum, loadMore) {
        var type = 'is' + this.orderConfig;
        if (loadMore) {
          return {
            classRid: goodsClassId,
            isPage: true,
            pageNum: pageNum,
            length: this.pageSize,
            [this.orderType]: this.orderDre,
          };
        } else {
          return {
            classRid: goodsClassId,
            isPage: true,
            pageNum: 1,
            length: this.pageSize * pageNum,
            [this.orderType]: this.orderDre,
          };
        }
      },

      async queryClassifyInfor(index, from) {

        var goodsClassCodeLeve1 = this.secList[0].goodsClassCode
        var goodsSecClassifyList = this.goodsClassifyInfor; // 二级分类信息
        var activeSecList = goodsSecClassifyList[index]; //当前页面数据信息
        var goodsClassId = activeSecList.goodsClassId; // 当前分类编码
        var totalCount = activeSecList.totalCount;
        var orderType = activeSecList.orderType;
        var orderDre = activeSecList.orderDre;
        var pageNum = activeSecList.pageNum; //当前分类页面
        this.comDetailDataList = goodsSecClassifyList[this.activeIndex].goodsList;
        //当排序规则发生改变时
        if (this.orderType != orderType || this.orderDre != orderDre) {
          activeSecList.orderType = this.orderType;
          activeSecList.orderDre = this.orderDre;
          activeSecList.pageNum = 1;
          var config = this.getConfig(goodsClassId, 1);
          var activeSecListInfo = await this.getGoodsInfor(config);
          activeSecList.goodsList = activeSecListInfo ? activeSecListInfo.results : activeSecList.goodsList;
          activeSecList.totalCount = activeSecListInfo.totalCount;
          hideLoading();
          this.comDetailDataList = goodsSecClassifyList[this.activeIndex].goodsList;
        } else if (activeSecList.goodsList.length == 0 && from != 'loadingMore') {
          //当数据为空的时候第一次申请数据
          this.animateLodding()
          var config = this.getConfig(goodsClassId, pageNum);
          var activeSecListInfo = await this.getGoodsInfor(config);
          activeSecList.goodsList = activeSecListInfo ? activeSecListInfo.results : activeSecList.goodsList;
          activeSecList.totalCount = activeSecListInfo.totalCount;
          hideLoading();
          this.comDetailDataList = goodsSecClassifyList[this.activeIndex].goodsList;
        } else if (totalCount > pageNum * this.pageSize) {
          //数据不为空的时候说明需要加载更多数据 并且有更多可申请数据时才继续执行下面方法
          activeSecList.pageNum++;
          this.isShowLoadMore = true;
          var config = this.getConfig(goodsClassId, ++pageNum, true);

          var activeSecListInfo = await this.getGoodsInfor(config);

          this.isShowLoadMore = false;
          this.finishPullUp()

          activeSecList.goodsList = activeSecListInfo
            ? activeSecList.goodsList.concat(activeSecListInfo.results)
            : activeSecList.goodsList;
          activeSecList.totalCount = activeSecListInfo.totalCount;
          hideLoading();
          this.comDetailDataList = goodsSecClassifyList[this.activeIndex].goodsList;
        } else {
          hideLoading()
        }
        this.saveLocal(goodsClassCodeLeve1, goodsSecClassifyList)
      },
      //调用借口申请分类数据
      async getGoodsInfor(config) {
        this.isOnLoad = true;
        var res = await queryGoodsList(config);
        res = res.data;
        this.isOnLoad = false;
        if (res.returncode == 0) {
          return '';
        }
        return res.data[0];
      },

      //保存数据到本地
      saveLocal(key, val) {
        console.log(key)
        localforage.setItem(key, val).then(() => {
          localforage.getItem(key).then(val => {
            console.log(val, 'valnnnnn', key)
          })
        })
      },

      async getInforLocal(index) {
        var classList = this.secList[0] || {}
        var key = classList.goodsClassCode || ''
        var goodsClassifyInfor = null
        if (key) {
          goodsClassifyInfor = await localforage.getItem(key)
        }
        if (goodsClassifyInfor) {
          this.goodsClassifyInfor = goodsClassifyInfor
        }
      },
      //获取华东窗口高度
      getWrpperHeight() {
        var wrpper = this.$refs.translateGroup;
        var wrpperHeight = wrpper.getWrpperHeight();
        this.wrpperHeight = wrpperHeight;
        return wrpperHeight;
      },
      //  获取滑动窗口距离顶部距离
      getWrpperTop() {
        var wrpper = this.$refs.translateGroup;
        var wrpperTop = wrpper.getWrpperTop();
        this.wrpperTop = wrpperTop;
        return wrpperTop;
      },

      //初始化分类信息
      async _initGoodsClassifyInfor() {
        console.log('4')
        var newData = this.secList;
        var activeIndex = this.activeIndex;
        var currentPage = this.currentPage;
        var orderDre = this.orderDre;
        var orderType = this.orderType;
        if (newData) {
          newData.forEach((item, index) => {
            item.pageNum = activeIndex == index ? currentPage : 1;
            item.pagePosition = 0;
            item.totalCount = 0;
            item.goodsList = [];
            item.orderDre = orderDre;
            item.orderType = orderType;
          });
          this.goodsClassifyInfor = newData;
        }
        await this.getInforLocal(this.activeIndex)
      },
      //刷新组件
      refresh() {
        this.$nextTick(() => {
          this.$refs.translateGroup && this.$refs.translateGroup.refresh();
          this.$refs.itemList && this.$refs.itemList.refresh();
        });
      },


      finishPullUp() {
        var translateGroup = this.$refs.translateGroup
        translateGroup && translateGroup.finishPullUp()
      },
      // 回到指定位置
      returnPos() {
        this.$nextTick(() => {
          this.$refs.translateGroup && this.$refs.translateGroup.returnPos();
        });
      },
      //将当前页面的分页页面 保存到vuex中以便返回的时候使用数据
      savePageNum() {
        if (this.activeSecList) {
          this.$store.commit('cjy/CHANGE_PAGE_NUM', this.activeSecList.pageNum);
        }
      },

      //初始化排序信息
      initOrder(data) {
        this.orderType = data.type; // 排序类型
        this.orderDre = data.order == 'down' ? 2 : 1; // 排序方向
      },

      changesTepSelectBox(data) {
        this.isTepSelectBox = data;
      },

      pullDown(data) {
        if (data > 0) {
          this.changesTepSelectBox(true);
        }
      },

      //改变头部tab栏显示状态
      changeIsShowTapHead(data) {
        this.$emit('changeIsShowTapHead', data);
      },

      //获取滚动窗口的高度
      getWrpperSize(data) {
        this.wrpperHeight = data.wrpperHeight;
        this.wrpperTop = data.wrpperTop;
      },

      changeIsReutrnPosition(data) {
        this.isReutrnPosition = data
      }
    },

    watch: {
      //二级分类列表改变时
      async secList(newData, oldData) {
        await this._initGoodsClassifyInfor(); // 初始化分类数据

        this.queryClassifyInfor(this.activeIndex); //获取对应的分类数据

      },

      activeIndex(index) {
        var code = this.$route.query.code;
        this.$router.replace({path: 'goodsClassify', query: {code: code, pageIndex: index}});
        this.queryClassifyInfor(index);
      },

      orderConfig(data) {
        this.initOrder(data);

        this.isinitOver && this.queryClassifyInfor(this.activeIndex);
      },

      //是否展示页面的分类切换
      isTepSelectBox(data) {
        this.changeIsShowTapHead(data);
      },

      //滚动条位置
      scrollY(data) {
        setTimeout(() => {
          if (data > this.tepSelectBoxHeight) {
            //如果滚动位置大于分类切换栏的位置那么 将头部的tab栏展示出来
            this.changeIsShowTapHead(false);
          } else if (this.isTepSelectBox) {
            // 如果滚动位置小于分类切换位置 并且分类切换处于展示状态那么将隐藏头部tab栏
            if (data == 0 && this.isReutrnPosition) {
            } else {
              this.changeIsShowTapHead(true);
            }
          }
        })
      },
    },
    computed: {
      ...mapState('cjy', {
        activeIndex: 'classifyIndex',
        classifyImageList: 'classifyImageList',
        orderConfig: 'orderConfig',
        scrollY: 'pagePosY',
      }),

      activeSecList() {
        var index = this.activeIndex;
        var goodsSecClassifyList = this.goodsClassifyInfor; // 二级分类信息
        var activeSecList = goodsSecClassifyList[index]; //当前页面数据信息
        return activeSecList;
      },
    },
    async created() {
      this.animateLodding();
      if (this.$store.state.cjy.isReturn) {
        this.currentPage = this.$store.state.cjy.pageNum || 1;
      } else {
        this.$store.commit('cjy/CHANGE_ORDER_CONFIG');
      }
      this.initOrder(this.orderConfig);
      await this._initGoodsClassifyInfor();
      this.isinitOver = true
      this.queryClassifyInfor(this.activeIndex, 'created');

    },
    mounted() {
    },
    updated() {
      this.$nextTick(() => {
        var tepSelectBox = this.$refs.tepSelectBox;
        var translateGroup = this.$refs.outer;
        if (translateGroup) {
          this.topHeight = translateGroup.offsetHeight;
        }
        if (tepSelectBox) {
          this.tepSelectBoxHeight = tepSelectBox.offsetHeight;
        }
      });
      this.refresh();
    },
  };
</script>

<style>
  .cjy-classify-list {
    width: 100%;
    height: 100%;
  }
</style>
